package com.magenta.maxoptra.geocoding.geoinformsputnik;

import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.params.AuthPolicy;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.impl.client.DefaultProxyAuthenticationHandler;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * User: Zlygostev
 * Date: 03.06.12
 * Time: 15:14
 */
public class HttpHelper {
    public static void applyProxy(AbstractHttpClient httpClient) {
        final String proxyHost = System.getProperty("http.proxyHost");
        if (proxyHost != null) {
            final String proxyPortStr = System.getProperty("http.proxyPort");
            Integer proxyPort = 80;
            if (proxyPortStr != null) {
                proxyPort = Integer.valueOf(proxyPortStr);
            }
            final String proxyUser = System.getProperty("http.proxyUser");
            final String proxyPsw = System.getProperty("http.proxyPassword");

            HttpHost proxy = new HttpHost(proxyHost, proxyPort);
            httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

            //AuthScope authScope = new AuthScope(proxyHost, proxyPort);
            if (proxyUser != null && proxyPsw != null) {
                Credentials credentials = new UsernamePasswordCredentials(proxyUser, proxyPsw);
                httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials);
                httpClient.setProxyAuthenticationHandler(new ProxyAuthHandler());
            } else {
                System.out.print("not defined proxy user or password");
            }
        }
    }

    private static class ProxyAuthHandler extends DefaultProxyAuthenticationHandler {
        private static final ProxyAuthHandler instance = new ProxyAuthHandler();

        private static final List<String> SCHEME_PRIORITY =
                Collections.unmodifiableList(Arrays.asList(
                        AuthPolicy.BASIC,
                        AuthPolicy.NTLM,
                        AuthPolicy.SPNEGO,
                        AuthPolicy.DIGEST
                ));

        @Override
        protected List<String> getAuthPreferences() {
            return SCHEME_PRIORITY;
        }

        public static ProxyAuthHandler getInstance() {
            return instance;
        }

    }
}
